package com.newland.rbac.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.newland.rbac.config.jwt.JwtProperties;
import com.newland.rbac.config.jwt.JwtTokenUtil;
import com.newland.rbac.model.User;
import com.newland.rbac.service.UserService;
import com.newland.utils.AjaxResponse;
import com.newland.utils.CustomException;
import com.newland.utils.CustomExceptionType;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 注册用户，随机盐+hash加密密码
     *
     * @param user
     * @return
     */
    @PostMapping("register")
    @RequiresPermissions("user/register")
    public AjaxResponse register(@RequestBody User user) {
        try {
            userService.save(user);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResponse.error(new CustomException(CustomExceptionType.OTHER_ERROR, e.getMessage()));
        }
        return AjaxResponse.success();
    }

    /**
     * 用户登录，使用用户主身份换取token
     *
     * @param map
     * @return
     */
    @PostMapping("login")
    public AjaxResponse login(@RequestBody Map<String, String> map) {
        String username = map.get(jwtProperties.getPrincipal());
        String password = map.get(jwtProperties.getPassword());
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, "用户名或密码不能为空"));
        }
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("name",username);
        User user = userService.getOne(userQueryWrapper);
        if(null==user){
            return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, "未知用户"));
        }else{
            Md5Hash md5Hash = new Md5Hash(password, user.getSalt(), 1024);
            if(!md5Hash.toHex().equals(user.getPwd())){
                return AjaxResponse.error(new CustomException(CustomExceptionType.USER_INPUT_ERROR, "密码错误"));
            }
        }
        long currentTimeMillis = System.currentTimeMillis();
        String token = jwtTokenUtil.generateToken(username,currentTimeMillis);
        stringRedisTemplate.opsForValue().set(username,String.valueOf(currentTimeMillis),jwtProperties.getRedisexpiration(), TimeUnit.MILLISECONDS);
        return AjaxResponse.success(token);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @PostMapping("logout")
    @RequiresAuthentication
    public AjaxResponse logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return AjaxResponse.success();
    }

}
